package com.chukun.concurrency.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 线程屏障的超时时间的使用
 */
@Slf4j
public class CyclicBarrierWithTimeOutOperator {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i=1;i<10;i++){
            final int threadNum=i;
            Thread.sleep(1000);
            executorService.execute(()->{
                 try{
                     race(threadNum);
                 }catch (Exception e){
                     log.error("exception ",e);
                 }
            });
        }
        executorService.shutdown();
    }

    public static void race(int i)throws Exception{
        Thread.sleep(1000);
        log.info("thread-"+i+" is ready");
        try {
            cyclicBarrier.await(2000, TimeUnit.MILLISECONDS);
        }catch (Exception e){
            log.error("exception ",e);
        }
        log.info("{} exec",i);
    }
}
